package ru.niir.goodfil.ui.tasks;

import it.sauronsoftware.cron4j.InvalidPatternException;
import it.sauronsoftware.cron4j.Scheduler;
import org.apache.log4j.Logger;
import ru.niir.goodfil.db.Client;
import ru.niir.goodfil.db.GoodfilFactory;
import ru.niir.goodfil.db.RestsExport;
import ru.niir.goodfil.db.handlers.Goodfil;
import ru.niir.goodfil.ui.scheduler.SchedulerManager;
import ru.niir.goodfil.ui.utils.RestsExportManager;

import java.util.TimerTask;

public class SchedulerRefreshTask extends TimerTask
{
    private static final Logger logger = Logger.getLogger(SchedulerRefreshTask.class);

    @Override
    public void run()
    {
        logger.debug("SchedulerRefreshTask call");

        Goodfil gf = GoodfilFactory.getInstance();

        if (SchedulerManager.getScheduler() != null && SchedulerManager.getScheduler().isStarted())
        {
            logger.debug("Stopping scheduler");
            SchedulerManager.getScheduler().stop();
        }

        SchedulerManager.setScheduler(new Scheduler());
        for (RestsExport re : gf.getRestsExports())
        {
            final long clientId = re.getClientId();
            logger.trace("Client " + clientId + ": " + re.getCrontab());

            try
            {
                SchedulerManager.getScheduler().schedule(re.getCrontab(), new Runnable()
                {
                    public void run()
                    {
                        Goodfil gf = GoodfilFactory.getInstance();
                        Client client = gf.getClientById(clientId);
                        String companyName = client.getCompanyName();
                        String email = client.getContactEmail();
                        try
                        {
                            RestsExportManager.sendSafe(gf, clientId);
                            logger.debug("Rests were sent for client : " + companyName + " " + email);
                        }
                        catch (Exception e)
                        {
                            logger.debug("Rests were NOT sent for client : " + companyName + " " + email + ": " + e.getMessage(), e);
                        }

                        try
                        {
                            gf.relealse();
                        }
                        catch (Exception e)
                        {
                        }
                    }
                });
            }
            catch (InvalidPatternException e)
            {
                logger.error("Bad pattern for client: " + clientId);
            }
        }
        SchedulerManager.getScheduler().start();
    }
}
